package com.ajaxw.analyser;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Indexer {
	private Map<String, ArrayList<Integer>> invt;

	public Indexer() {
		this.invt = new HashMap<String, ArrayList<Integer>>();
	}

	public void add(String key, int docId) {
		if (this.invt.containsKey(key)) {
			this.invt.get(key).add(docId);
		} else {
			ArrayList<Integer> arr = new ArrayList<Integer>();
			arr.add(docId);
			this.invt.put(key, arr);
		}
	}

	public void dump() throws IOException {
		String dir = "E:\\tmp\\";
		DataOutputStream ddos = new DataOutputStream(new FileOutputStream(
				new File(dir + "dict.dat"), true));
		DataOutputStream idos = new DataOutputStream(new FileOutputStream(
				new File(dir + "invt.dat"), true));
		DataOutputStream qdos = new DataOutputStream(new FileOutputStream(
				new File(dir + "input.dat"), true));

		Iterator<String> keys = this.invt.keySet().iterator();

		int off = 0;
		while (keys.hasNext()) {
			String key = keys.next();
			ArrayList<Integer> arr = this.invt.get(key);
			if (arr.size() < 1)
				continue;

			ddos.writeInt(arr.size());
			ddos.writeInt(off);

			qdos.writeInt(Integer.SIZE / 8 + key.getBytes().length);
			qdos.writeInt(arr.size());
			qdos.writeInt(off);
			qdos.writeBytes(key);

			for (int id : arr) {
				idos.writeInt(id);
			}
		}

		ddos.close();
		idos.close();
		qdos.close();
	}
}
